/**
 * @(#)BaiduBaikeService.java, 2013-2-14. Copyright 2013 RENREN, Inc. All rights
 *                             reserved. RENREN PROPRIETARY/CONFIDENTIAL. Use is
 *                             subject to license terms.
 */
package com.wennimei.service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wennimei.dao.BaiduBaikeDAO;
import com.wennimei.domain.baidu.Baike;
import com.wennimei.enums.MessageTypeEnum;
import com.wennimei.util.Switcher;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class BaiduBaikeService {
    private static Logger log = Logger.getLogger(BaiduBaikeService.class);

    @Autowired
    private BaiduBaikeDAO baiduBaikeDAO;
    
    @Autowired
    private Switcher switcher;

    private final ScheduledExecutorService scheduled = Executors
            .newScheduledThreadPool(1);

    private static volatile AtomicInteger id = new AtomicInteger(0);

    void init() {
        scheduled.scheduleWithFixedDelay(new Runnable() {

            @Override
            public void run() {
                
                if(!switcher.isOpen())
                    return;
                
                final String url = "http://wapbaike.baidu.com/view/%s.htm";
                Integer maxId = baiduBaikeDAO.getMaxId();
                maxId = null == maxId ? 0 : maxId;
                id.addAndGet(maxId);

                for (int i = 0; i < 10; i++) {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            long start = System.currentTimeMillis();
                            HttpClient client = new HttpClient();
                            while (true) {
                                if (System.currentTimeMillis() - start > 30 * 60 * 1000)
                                    return;
                                int max = id.getAndAdd(1);
                                log.info("start crawl baidubaike " + max);
                                try {
                                    GetMethod m = new GetMethod(String.format(
                                            url, max));
                                    client.executeMethod(m);
                                    String html = new String(m
                                            .getResponseBody(), "utf-8");
                                    if (!html.contains("summary"))
                                        continue;
                                    String _html = html.trim()
                                            .replaceAll("[\\s]", "")
                                            .replaceAll(" ", "")
                                            .replaceAll("\\t", "")
                                            .replaceAll("\\r", "")
                                            .replaceAll("\\n", "");
                                    Pattern pattern = Pattern
                                            .compile(".*<h1>(.*)</h1>.*");
                                    Matcher matcher = pattern.matcher(_html);
                                    String title = null;
                                    while (matcher.find()) {
                                        title = matcher.group(1);
                                        break;
                                    }
                                    if (null == title)
                                        continue;
                                    title = title.replaceAll("<[^>]+>", "")
                                            .replaceAll("\\(.*\\)", "")
                                            .replaceAll("（.*）", "");

                                    String summary = null;
                                    Pattern pattern2 = Pattern
                                            .compile(".*<pclass=\"summary\">(.*)</p><div.*");
                                    Matcher matcher2 = pattern2.matcher(_html);
                                    while (matcher2.find()) {
                                        summary = matcher2.group(1);
                                        break;
                                    }
                                    if (null == summary)
                                        continue;
                                    summary = summary.replaceAll("<[^>]+>", "");

                                    baiduBaikeDAO.insert(max, title, summary,
                                            null);
                                    log.info("crawl baidubaike " + title);
                                } catch (Exception e) {
                                    log.error("crawl baidubaike error", e);
                                }
                            }

                        }
                    }).start();
                }

            }
        }, 0, 1, TimeUnit.DAYS);
    }

    public String get(String content) {
        content = content.replaceAll(
                MessageTypeEnum.BAIDU_BAIKE.getReplaceRegx(), "");
        Baike result = this.baiduBaikeDAO.get(content);
        return result.getSummary() + " 详细: http://wapbaike.baidu.com/view/"
                + result.getId() + ".htm 来源:百度百科";
    }
}
